package com.example.infrastructure.api.advice;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.persistence.EntityNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author lxh
 * @date 2020/11/17 下午6:12
 **/
@RestControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleBindException(BindException e) {
        FieldError error = e.getFieldError();
        HashMap<String, String> map = new HashMap<>(1);
        map.put(error.getField(), error.getDefaultMessage());
        return map;
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleIllegalArgumentException(IllegalArgumentException e) {
        HashMap<String, String> map = new HashMap<>(1);
        map.put("msg", e.getMessage());
        return map;
    }

    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Map<String, String> handleEntityNotFoundException(EntityNotFoundException e) {
        HashMap<String, String> map = new HashMap<>(1);
        map.put("msg", e.getMessage());
        return map;
    }
}
